package com.example.chaindemo.web.version;

import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.Assert;
import org.springframework.web.servlet.mvc.condition.RequestCondition;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @author YDF
 * @date 2019/12/16
 */
public class CustomRequestMappingHandlerMapping extends RequestMappingHandlerMapping {

    @Override
    protected RequestCondition<?> getCustomTypeCondition(Class<?> handlerType) {
        ApiVersion version = AnnotationUtils.getAnnotation(handlerType, ApiVersion.class);
        return createRequestCondition(version);
    }

    @Override
    protected RequestCondition<?> getCustomMethodCondition(Method method) {
        ApiVersion version = AnnotationUtils.getAnnotation(method, ApiVersion.class);
        return createRequestCondition(version);
    }

    private RequestCondition<?> createRequestCondition(ApiVersion version) {
        if (Objects.isNull(version)) {
            return null;
        }
        int value = version.value();
        Assert.isTrue(value >= 1, "Api版本号必须大于或等于1");
        return new ApiVersionCondition(value);
    }
}
